package cn.tworice.blog.service.impl;

import cn.tworice.blog.dao.ToolsDao;
import cn.tworice.blog.entity.CountIp;
import cn.tworice.blog.entity.ErrorInfo;
import cn.tworice.blog.service.ToolsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Date;

@Service
@Slf4j
public class ToolsServiceImpl implements ToolsService {

    @Autowired
    private ToolsDao toolsDao;

    @Value("${blog.QSchoolPath}")
    private String qSchoolPath;


    /**
     * 统计IP和请求地址
     * @param countIp
     */
    @Override
    public void saveCallIP(CountIp countIp) {
        toolsDao.saveCallIP(countIp);
    }

    /**
     * 保存错误信息到数据库
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public void saveErrorInfo(ErrorInfo error) {


        try {
            error.setTime(new Date().getTime());
            toolsDao.saveErrorInfo(error);
        }catch (Exception ex){
            log.error("保存报错信息到数据库时出现异常-"+ex.getMessage());
        }
    }


    /**
     * Q校园一键签到
     * @author 二饭
     * @email 1786705138@qq.com
     */
    @Override
    public String signIn() throws Exception {
        String shell=qSchoolPath + "/login.sh";
        // 执行登录
        Process process = Runtime.getRuntime().exec(shell);
        process.waitFor();// 等待脚本执行完毕

        // 返回cookie中的JSESSIONID
        String result=getCookie(qSchoolPath+"/a.txt");

        Process ps=Runtime.getRuntime().exec(new String[]{"/home/save.sh",result});
        ps.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        result = sb.toString();

        return result;
    }

    /**
     * 从文件中获取Cookie
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public String getCookie(String path) throws Exception{
        FileReader fileReader = null;
        String s=null;
        try{
            fileReader= new FileReader(new File(path));
            char[] chars=new char[1024];
            fileReader.read(chars);
            s=new String(chars);

            int i=s.indexOf("JSESSIONID");
            s=s.substring(i+11);
            s=s.trim();
            System.out.println(s);
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {

            fileReader.close();
        }

        return s;
    }
}
